package com.lgt_enterprise_android.view.fragments;


import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.lgt_enterprise_android.Constant;
import com.lgt_enterprise_android.R;
import com.lgt_enterprise_android.base.CommonDialog;
import com.lgt_enterprise_android.utils.BasicHttp;
import com.lgt_enterprise_android.utils.CheckUpdate;
import com.lgt_enterprise_android.utils.CommonUtil;
import com.lgt_enterprise_android.utils.HttpManager;
import com.lgt_enterprise_android.utils.PrefBigDataUtils;
import com.lgt_enterprise_android.utils.PrefUtils;
import com.lgt_enterprise_android.utils.StringUtil;
import com.lgt_enterprise_android.view.pages.LoginActivity;
import com.lgt_enterprise_android.view.pages.b.workors.MyWorkersActivity;
import com.lgt_enterprise_android.view.pages.me.EditPasswordActivity;
import com.lgt_enterprise_android.view.pages.me.EditPhoneNumberActivity;
import com.lgt_enterprise_android.view.pages.me.EnterpriseActivity;
import com.lgt_enterprise_android.view.pages.me.ProfileInfoActivity;
import com.util.AppUtil;

import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;


/**
 * A simple {@link Fragment} subclass.
 */
public class MeFragment extends Fragment implements EasyPermissions.PermissionCallbacks {

    public static JSONObject jsonEnterprise;
    public static JSONObject jsonProfileInfo;


    public MeFragment() {
        // Required empty public constructor
    }

    public static MeFragment newInstance(String param1, String param2) {
        MeFragment fragment = new MeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_me, container, false);
    }


    @Override
    public void onResume() {
        super.onResume();
        if (!isHidden()) {
            HttpManager.getCompanyInfo(getActivity(), new BasicHttp.IMyCallBack() {
                @Override
                public void onResponse(Object resonseObj) {
                    jsonEnterprise = (JSONObject) resonseObj;

                    if (jsonEnterprise == null) {
                        PrefBigDataUtils.setSharedPrefStringData(getActivity(), PrefBigDataUtils.COMPANY_INFO, "");
                        return;
                    }
                    PrefBigDataUtils.setSharedPrefStringData(getActivity(), PrefBigDataUtils.COMPANY_INFO, jsonEnterprise.toJSONString());
                }

                @Override
                public void onFailure(String mes) {

                }
            });

            HttpManager.getProfileInfo(getActivity(), new BasicHttp.IMyCallBack() {
                @Override
                public void onResponse(Object resonseObj) {
                    jsonProfileInfo = ((JSONObject) resonseObj);
                    if (jsonProfileInfo == null) {
                        PrefBigDataUtils.setSharedPrefStringData(getActivity(), PrefBigDataUtils.PERSONAL_INFO, "");
                        return;
                    }
                    PrefBigDataUtils.setSharedPrefStringData(getActivity(), PrefBigDataUtils.PERSONAL_INFO, jsonProfileInfo.toJSONString());
                    String strTitle = jsonProfileInfo.getString("name");
                    if (StringUtil.isEmpty(strTitle)) {
                        strTitle = jsonProfileInfo.getString("phoneNumber");
                    }
                    ((TextView) getActivity().findViewById(R.id.me_txt_name)).setText(strTitle);

                    ImageView img = (ImageView) getActivity().findViewById(R.id.me_img_head);
                    Glide.with(getActivity()).applyDefaultRequestOptions(CommonUtil.getCircelGlideOptions()).load(jsonProfileInfo.getString("avatarUrl")).into(img);
                }

                @Override
                public void onFailure(String mes) {

                }
            });

        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        new Thread(new Runnable() {
            @Override
            public void run() {
                String companyInfo = PrefBigDataUtils.getSharedPrefString(getActivity(), PrefBigDataUtils.COMPANY_INFO);
                if (!StringUtil.isEmpty(companyInfo)) {
                    jsonEnterprise = JSONObject.parseObject(companyInfo);
                }
                String personalInfo = PrefBigDataUtils.getSharedPrefString(getActivity(), PrefBigDataUtils.PERSONAL_INFO);
                if (!StringUtil.isEmpty(personalInfo)) {
                    jsonProfileInfo = JSONObject.parseObject(personalInfo);
                }
            }
        }).start();

        ((TextView) (getActivity().findViewById(R.id.txt_version))).setText("V" + AppUtil.getVersionName(getActivity()));


        (getActivity().findViewById(R.id.lin_check_version)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               new CheckUpdate().checkUpgrade(getActivity(),true);
            }
        });

        (getActivity().findViewById(R.id.me_enter_info)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), EnterpriseActivity.class);
                startActivity(intent);
            }
        });

        (getActivity().findViewById(R.id.lin_me_workers)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), MyWorkersActivity.class);
                startActivity(intent);
            }
        });


        (getActivity().findViewById(R.id.me_txt_name)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MeFragment.jsonProfileInfo != null) {
                    Intent intent = new Intent(getActivity(), ProfileInfoActivity.class);
                    startActivity(intent);
                }
            }
        });

        (getActivity().findViewById(R.id.lin_edit_password)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), EditPasswordActivity.class);
                startActivity(intent);
            }
        });

        (getActivity().findViewById(R.id.lin_edit_phone)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), EditPhoneNumberActivity.class);
                startActivity(intent);
            }
        });

        (getActivity().findViewById(R.id.txt_phone)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] perms = {Manifest.permission.CALL_PHONE};
                if (EasyPermissions.hasPermissions(getActivity(), perms)) {
                    dial(view.getTag().toString());
                } else {
                    EasyPermissions.requestPermissions(getActivity(), "需要电话权限", 101, perms);
                }
            }
        });


        (getActivity().findViewById(R.id.lin_logout)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final CommonDialog dialog = new CommonDialog(getActivity());
                dialog.setMessage("您确定要退出吗？")
                        .setTitle("提示").setNegtive("取消")
                        .setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
                            @Override
                            public void onPositiveClick() {
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                Constant.token = "";
                                PrefBigDataUtils.setSharedPrefStringData(getActivity(),PrefBigDataUtils.PERSONAL_INFO,"");
                                PrefBigDataUtils.setSharedPrefStringData(getActivity(),PrefBigDataUtils.COMPANY_INFO,"");
                                PrefUtils.setSharedPrefStringData(getActivity(), PrefUtils.TOKEN, "");
                                startActivity(intent);
                                dialog.dismiss();
                                getActivity().finish();
                            }

                            @Override
                            public void onNegtiveClick() {
                                dialog.dismiss();
                            }
                        }).show();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        dial(getActivity().findViewById(R.id.txt_phone).getTag().toString());
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

    private void dial(final String number) {
        final CommonDialog dialog = new CommonDialog(getActivity());
        dialog.setMessage(number)
                .setTitle("拨打电话").setNegtive("取消").setPositive("呼叫")
                .setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
                    @Override
                    public void onPositiveClick() {
                        Intent intent = new Intent(Intent.ACTION_CALL);
                        Uri data = Uri.parse("tel:" + number);
                        intent.setData(data);
                        startActivity(intent);
                        dialog.dismiss();
                    }

                    @Override
                    public void onNegtiveClick() {
                        dialog.dismiss();
                    }
                }).show();
    }
}
